package base.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 资源类
class LTicket {
    private int ticketNum = 30;
    private final Lock lock = new ReentrantLock();

    public synchronized void sale() {

        // 上锁
        lock.lock();
        try {

            if (ticketNum > 0) {
                System.out.println(Thread.currentThread().getName() + "卖的，" + "剩余票数：" + (--ticketNum));
            }
        } finally {
            lock.unlock();
        }


    }
}

// lock接口的使用
public class LockDemo {


    public static void main(String[] args) {
        LTicket lTicket = new LTicket();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    lTicket.sale();
                }

            }
        }, "AA").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    lTicket.sale();
                }
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                lTicket.sale();
            }
        }, "CC").start();
    }
}
